// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import uView from '@/uni_modules/uview-ui'
import appStore from '@/store'
import store from '@/store/store.js'
import address from '@/utils/address'
import config from '@/utils/config.js'
import { getNotReadMessage } from '@/api/message'

Vue.config.productionTip = false
Vue.prototype.$appStore = appStore
Vue.prototype.$store = store
Vue.prototype.config = config
Vue.use(uView)

uni.$u.setConfig({
   color: {
      primary: '#00a679'
   }
})

let isToast = false
Vue.prototype.$toast = {
   show: ({msg = '加载中', t = 2, position = 'bottom'}) => {
      if(isToast) {
         uni.hideToast()
      }
      uni.showToast({
         icon: 'none',
         duration: t * 1000,
         title: msg,
         mask: true,
         position
      })
   },
   hide: () => {
      uni.hideToast()
   }
}

Vue.prototype.$loading = {
	show: (msg = '加载中...') => {
		uni.showLoading({
			mask: true,
			title: msg
		})
	},
	hide: () => {
		uni.hideLoading()
	} 
}

uni.addInterceptor('navigateTo', {
   invoke: (args) => {
      // uni.$on('hideLoading')
      // console.log('navigateTo', args);
      // return true
   },
   success: (res) => {
      // console.log('navigateTo', res);
      // return true
   }
})

uni.addInterceptor('navigateBack', {
   invoke: (args) => {
      // console.log('navigateBack', args);
      return true
   },
   success: (res) => {
      // console.log('navigateBack', res);
      return true
   }
})

uni.addInterceptor('socket', {
   invoke: (args) => {
      console.log(args);
   },
   success: (res) => {
      console.log(res);
   }
})

let socket
const connectSocket = () => {
   uni.closeSocket()
   socket = uni.connectSocket({
      url: address.socketURL + '?' + store.getters.id,
      complete: () => {},
   })
   Vue.prototype.socket = socket
}
if(store.getters.id) {
   connectSocket() 
   socket.onOpen(e => {
      console.log('服务连接成功')
   })
   socket.onError(e => {
      console.log('服务连接失败')
   })
   socket.onClose(e => {
      console.log('断开连接')
   })
   socket.onMessage(({ data }) => {
      getNotReadMessage(store.getters.id).then(res => {
         const { code, data } = res
			if(code === 200) {
				store.commit('UPDATE_MESSAGE', data)
			}
      })
   })
}

let isLogin = false
uni.addInterceptor('request', {
   invoke: (args) => {
      if(args.url.indexOf('/login') != -1) {
         isLogin = true
      }else {
         isLogin = false
      }
   },
   success: (res) => {
      if(isLogin) {
         socket || connectSocket()
      }
   }
})

Vue.prototype.fileUrl = address.fileUrl

App.mpType = 'app'

const app = new Vue({
   ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
   const app = createSSRApp(App)
   return {
      app
   }
}
// #endif